package com.dragon.test.hibernate.manytomany.action;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.dragon.test.hibernate.manytomany.bean.Role;
import com.dragon.test.hibernate.manytomany.bean.User;


/**
 * 多对多级联操作
 * @author SmallDragon
 *
 */
public class ManyToMany {

	public static void main(String[] args) {
		Configuration configuration = new Configuration();
		configuration.configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.getCurrentSession();

		
		
		session.close();
		sessionFactory.close();
	}
	
	/**
	 * 级联保存
	 */
	@Test
	public void testSave() {
		Configuration configuration = new Configuration();
		configuration.configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		
		
		User user1 = new User();
		user1.setuName("jack");
		user1.setuPassword("123");
		User user2 = new User();
		user2.setuName("rose");
		user2.setuPassword("456");
		
		Role role1 = new Role();
		role1.setrName("经理");
		role1.setrMemo("经理");
		Role role2 = new Role();
		role2.setrName("秘书");
		role2.setrMemo("秘书");
		Role role3 = new Role();
		role3.setrName("保安");
		role3.setrMemo("保安");
		
		//实体之间建立关系
		user1.getRoles().add(role1);
		user1.getRoles().add(role2);
		user2.getRoles().add(role2);
		user2.getRoles().add(role3);
		
		session.save(user1);
		session.save(user2);
		
		
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
	

}
